package com.lwk.web.action;

import java.util.List;

import org.apache.struts2.StrutsStatics;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.lwk.domain.Admin;
import com.lwk.service.AdminService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminAction extends ActionSupport implements ModelDriven<Admin> {

    private Admin admin = new Admin();

    @Override
    public Admin getModel() {
        // TODO Auto-generated method stub
        return admin;
    }

    // 注入Service
    private AdminService adminService;

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }
    //管理员登录
    public String login() {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
        String autoLogin = request.getParameter("auto");
        System.out.println(autoLogin);
        DetachedCriteria dc = DetachedCriteria.forClass(Admin.class);
        dc.add(Restrictions.eq("username", admin.getUsername()));
        dc.add(Restrictions.eq("password", admin.getPassword()));
        List<Admin> list = adminService.login(dc);
        if (list.size() != 0) {
            if ("true".equals(autoLogin)) {
                String str = admin.getUsername() + "-" + admin.getPassword();
                Cookie cookie = new Cookie("user", str);
                cookie.setMaxAge(60 * 3);
                HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
                response.addCookie(cookie);
            }
            ActionContext.getContext().getSession().put("user", list.get(0));
            return "index";
        }
        return "error";
    }
}
